<template>
	<view class="cake-cont">
		<custom-nav/>
		<view class="tab-cont flex padding justify-around">
			<view 
				v-for="(item,index) in tabArr" 
				:class="index==tabIdx?'':'text-gray'"
				@click="handleTab(index)"
			>
				{{item.name}}
			</view>
		</view>
		<view class="cake-list flex flex-wrap justify-between">
			<cake-item v-for="item in cakeList" :gdata="item"/>
		</view>
	</view>
</template>

<script>
import { cakeGet } from '../../api/cake';
import { $http } from '../../utils/http';
	export default {
		data() {
			return {
				cakeList:[],
				page:0,
				tabArr:[
					{name:'蛋糕',bcid:1},
					{name:'面包',bcid:11},
					{name:'小食',bcid:6},
					{name:'配件',bcid:5},
				],
				tabIdx:0
			};
		},
		methods: {
			//分类菜单切换
			async handleTab(idx) {
				this.tabIdx = idx
				let {bcid} = this.tabArr[idx]
				this.page = 0
				let res = await cakeGet(0,bcid)
				this.cakeList = res.data.results
			}
		},
		async onLoad() {
			console.log('页面的onLoad');
			//方法1:
			// uni.request({
			// 	url:'https://api2304.h5project.cn/1.1/classes/Cake',
			// 	header:{
			// 		'X-LC-Id':'G6HU8PIbCl2Dm4DLVWt8mLmo-gzGzoHsz',
			// 		'X-LC-Key':'lBuHPedslBnd7iHWxMW60rO0',
			// 		'content-type':'application/json',
			// 	},
			// 	success: (res) => {
			// 		console.log(res);
			// 		this.cakeList = res.data.results
			// 	}
			// })
			
			// 方法2: 自己封装uni.request
			// let res = await $http('/classes/Cake')
			// this.cakeList = res.data.results
			
			// 方法3: 第三方库请求
			let res = await cakeGet()
			this.cakeList = res.data.results
			this.page++
		},
		async onReachBottom() {
			console.log('触底了');
			// 使用新的页码获取新的数据
			let {tabArr,tabIdx} = this
			let {bcid} = tabArr[tabIdx]
			let res = await cakeGet(this.page,bcid)
			//将新数据追加到旧数据中
			let {results} = res.data
			if(results.length){
				this.cakeList = [
					...this.cakeList,
					...results
				]
				this.page++
				return
			}
			uni.showToast({
				title:'没有更多了',
				icon:'none'
			})
		},
		async onPullDownRefresh() {
			console.log('下拉刷新了');
			this.page = 0
			let res = await cakeGet()
			uni.stopPullDownRefresh() // 关闭下拉刷新动画
			this.cakeList = res.data.results
		}
	}
</script>

<style lang="scss">
.cake-list{
	padding: 14upx;
}
.tab-cont view{
	position: relative;
	width: 25%;
	text-align: center;
	&::after{
		content: '';
		position: absolute;
		right: 0;
		top: 50%;
		width: 1px;
		height: 25upx;
		transform: scaleX(0.5) translateY(-50%);
		background-color: #d8d8d8;
	}
	&:last-child::after{
		width: 0;
	}
}
.cake-cont{
	padding-top: 100upx;
}
</style>
